<template>
  <div class="edit-travel-note-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1>编辑游记</h1>
      <p class="subtitle">修改你的旅行记录</p>
    </div>

    <!-- 加载状态 -->
    <div
      v-if="loading"
      class="loading-container"
      v-loading="loading"
      element-loading-text="加载中..."
    >
      <div style="height: 400px"></div>
    </div>

    <!-- 主内容区域 -->
    <div v-else class="main-content">
      <el-card class="form-card" shadow="hover">
        <el-form
          ref="formRef"
          :model="form"
          :rules="rules"
          label-width="100px"
          class="travel-note-form"
        >
          <!-- 标题 -->
          <el-form-item label="游记标题" prop="title">
            <el-input
              v-model="form.title"
              placeholder="请输入游记标题"
              maxlength="100"
              show-word-limit
              clearable
              size="large"
            />
          </el-form-item>

          <!-- 选择城市 -->
          <el-form-item label="旅行城市" prop="city">
            <el-select
              v-model="form.city"
              placeholder="选择旅行城市"
              filterable
              allow-create
              default-first-option
              clearable
              size="large"
            >
              <el-option
                v-for="city in popularCities"
                :key="city.value"
                :label="city.label"
                :value="city.value"
              />
            </el-select>
          </el-form-item>

          <!-- 旅行日期 -->
          <el-form-item label="旅行日期" prop="startDate">
            <el-date-picker
              v-model="form.startDate"
              type="date"
              placeholder="选择旅行日期"
              value-format="YYYY-MM-DD"
              size="large"
              style="width: 100%"
            />
          </el-form-item>

          <!-- 简介 -->
          <el-form-item label="游记简介" prop="description">
            <el-input
              v-model="form.description"
              type="textarea"
              :rows="3"
              placeholder="简单描述你的旅程..."
              maxlength="200"
              show-word-limit
            />
          </el-form-item>

          <!-- 游记内容 -->
          <el-form-item label="游记内容" prop="content">
            <div>
              <!-- 工具栏 -->
              <div id="toolbar-container" style="border: 1px solid #ccc; border-bottom: none; background-color: #fafafa; padding: 4px 0;"></div>
              <!-- 编辑器 -->
              <div id="editor-container" style="height: 400px; overflow-y: auto; border: 1px solid #ccc; border-top: none;"></div>
            </div>
            <div style="text-align: right; color: #909399; margin-top: 10px;">
              {{ form.content.length }}/10000
            </div>
          </el-form-item>

          <!-- 标签 -->
          <el-form-item label="标签">
            <div class="tags-container">
              <el-tag
                v-for="(tag, index) in form.tags"
                :key="tag"
                closable
                @close="form.tags.splice(index, 1)"
                class="tag-item"
              >
                {{ tag }}
              </el-tag>
              <el-input
                v-if="form.tags.length < 6"
                v-model="inputTag"
                placeholder="输入标签后按回车"
                size="small"
                class="tag-input"
                @keyup.enter="handleTagInput"
                maxlength="10"
              />
            </div>
          </el-form-item>

          <!-- 可见性设置 -->
          <el-form-item label="可见性" prop="visibility">
            <el-radio-group v-model="form.visibility" size="large">
              <el-radio value="public">公开</el-radio>
              <el-radio value="private">私密</el-radio>
            </el-radio-group>
            <div class="form-tip">
              <el-icon><InfoFilled /></el-icon>
              设置为公开后需要管理员审核通过才能展示
            </div>
          </el-form-item>

          <!-- 操作按钮 -->
          <el-form-item>
            <div class="action-buttons">
              <el-button @click="goBack" size="large">取消</el-button>
              <el-button
                type="danger"
                @click="handleDelete"
                :loading="deleting"
                size="large"
              >
                删除游记
              </el-button>
              <el-button
                type="primary"
                @click="handleUpdate"
                :loading="submitting"
                size="large"
              >
                保存修改
              </el-button>
            </div>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { InfoFilled } from '@element-plus/icons-vue'
import { getTravelNoteDetail, updateTravelNote, deleteTravelNote } from '../../api/travelNote'
import { uploadImage } from '../../api/upload'
// 导入 wangeditor
import '@wangeditor/editor/dist/css/style.css' // 引入样式
import { createEditor, createToolbar } from '@wangeditor/editor'

const route = useRoute()
const router = useRouter()
const noteId = parseInt(route.params.id)

// 表单数据
const form = ref({
  title: '',
  city: '',
  startDate: '',
  description: '',
  content: '',
  tags: [],
  visibility: 'public'
})

// 热门城市
const popularCities = [
  { value: '北京', label: '北京' },
  { value: '上海', label: '上海' },
  { value: '广州', label: '广州' },
  { value: '深圳', label: '深圳' },
  { value: '成都', label: '成都' },
  { value: '杭州', label: '杭州' },
  { value: '西安', label: '西安' },
  { value: '南京', label: '南京' }
]

// 标签输入
const inputTag = ref('')

// 表单验证规则
const rules = {
  title: [
    { required: true, message: '请输入游记标题', trigger: 'blur' },
    { min: 5, message: '标题至少5个字符', trigger: 'blur' }
  ],
  city: [{ required: true, message: '请选择旅行城市', trigger: 'change' }],
  startDate: [{ required: true, message: '请选择旅行日期', trigger: 'change' }],
  content: [
    { required: true, message: '请输入游记内容', trigger: 'blur' },
    { min: 50, message: '内容至少50个字符', trigger: 'blur' }
  ]
}

const formRef = ref(null)
const loading = ref(true)
const submitting = ref(false)
const uploadingGallery = ref(false)
const deleting = ref(false)

// 编辑器实例
let editor = null
let toolbar = null

// 编辑器配置
const editorConfig = {
  placeholder: '分享你的旅行故事...',
  onChange(editor) {
    // 监听内容变化，更新 form.content
    form.value.content = editor.getHtml()
  },
  MENU_CONF: {
    // 配置上传图片
    uploadImage: {
      // 自定义上传
      async customUpload(file, insertFn) {
        uploadingGallery.value = true
        try {
          const result = await uploadImage(file)
          if (result.success && result.data && result.data.url) {
            insertFn(result.data.url) // 插入图片到编辑器
            ElMessage.success('图片插入成功')
          } else {
            throw new Error(result.message || '上传失败')
          }
        } catch (error) {
          console.error('上传图片失败:', error)
          ElMessage.error('上传图片失败：' + (error.message || '请重试'))
        } finally {
          uploadingGallery.value = false
        }
      }
    }
  }
}

// 工具栏配置
const toolbarConfig = {
  excludeKeys: ['fullScreen'] // 排除不需要的功能
}

// 初始化编辑器
const initEditor = () => {
  // 创建编辑器实例
  editor = createEditor({
    selector: '#editor-container',
    config: editorConfig,
    mode: 'default'
  })
  
  // 创建工具栏实例
  toolbar = createToolbar({
    editor,
    selector: '#toolbar-container',
    config: toolbarConfig
  })
  
  // 如果有内容，设置到编辑器中
  if (form.value.content) {
    editor.setHtml(form.value.content)
  }
}

// 销毁编辑器
const destroyEditor = () => {
  if (editor) {
    editor.destroy()
    editor = null
  }
  if (toolbar) {
    toolbar.destroy()
    toolbar = null
  }
}

// 加载游记详情
const loadNoteDetail = async () => {
  loading.value = true
  try {
    console.log('开始加载游记:', noteId)
    const result = await getTravelNoteDetail(noteId)
    console.log('加载结果:', result)

    if (result.success) {
      const note = result.data

      // 填充表单
      form.value = {
        title: note.title || '',
        city: note.city || '',
        startDate: note.start_date || '',
        description: note.description || '',
        content: note.content || '',
        tags: Array.isArray(note.tags)
          ? note.tags
          : note.tags
          ? typeof note.tags === 'string'
            ? JSON.parse(note.tags)
            : []
          : [],
        visibility: note.visibility || 'public'
      }

      console.log('表单数据:', form.value)
    } else {
      ElMessage.error(result.message || '加载失败')
      // 不立即返回，给用户看到错误信息的时间
      setTimeout(() => {
        goBack()
      }, 2000)
    }
  } catch (error) {
    console.error('加载游记失败:', error)
    ElMessage.error('加载失败：' + (error.message || '请重试'))
    // 不立即返回，给用户看到错误信息的时间
    setTimeout(() => {
      goBack()
    }, 2000)
  } finally {
    loading.value = false
  }
}

// 添加标签
const handleTagInput = () => {
  const tag = inputTag.value.trim()
  if (!tag) return

  if (form.value.tags.includes(tag)) {
    ElMessage.warning('标签已存在')
    return
  }

  if (form.value.tags.length >= 6) {
    ElMessage.warning('最多添加6个标签')
    return
  }

  form.value.tags.push(tag)
  inputTag.value = ''
}

// 更新游记
const handleUpdate = async () => {
  if (!formRef.value) return

  // 确保编辑器内容同步到表单
  if (editor) {
    form.value.content = editor.getHtml()
  }

  await formRef.value.validate(async (valid) => {
    if (!valid) {
      ElMessage.warning('请填写完整信息')
      return
    }

    submitting.value = true

    try {
      const updateData = {
        title: form.value.title,
        city: form.value.city,
        start_date: form.value.startDate,
        description: form.value.description,
        content: form.value.content,
        tags: JSON.stringify(form.value.tags),
        visibility: form.value.visibility
      }

      // 如果从私密改为公开，需要重新审核
      if (form.value.visibility === 'public') {
        updateData.status = 'pending'
      }

      const result = await updateTravelNote(noteId, updateData)

      if (result.success) {
        ElMessage.success('更新成功')
        // 跳转到详情页
        router.push(`/travel-note/${noteId}`)
      } else {
        ElMessage.error(result.message || '更新失败')
      }
    } catch (error) {
      console.error('更新游记失败:', error)
      ElMessage.error('更新失败：' + (error.message || '请重试'))
    } finally {
      submitting.value = false
    }
  })
}

// 返回
const goBack = () => {
  router.back()
}

// 删除游记
const handleDelete = async () => {
  try {
    const confirmResult = await ElMessageBox.confirm(
      '确定要删除这篇游记吗？此操作不可恢复。',
      '删除确认',
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning',
        confirmButtonClass: 'el-button--danger'
      }
    )

    if (confirmResult === 'confirm') {
      deleting.value = true
      const result = await deleteTravelNote(noteId)
      
      if (result.success) {
        ElMessage.success('游记删除成功')
        // 删除成功后跳转到游记列表页
        router.push('/travel-note')
      } else {
        ElMessage.error(result.message || '删除失败')
      }
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除游记失败:', error)
      ElMessage.error('删除失败：' + (error.message || '请重试'))
    }
  } finally {
    deleting.value = false
  }
}

// 加载数据
onMounted(async () => {
  await loadNoteDetail()
  // 延迟初始化，确保DOM已渲染并且数据已加载
  setTimeout(() => {
    initEditor()
  }, 100)
})

onBeforeUnmount(() => {
  destroyEditor()
})
</script>

<style scoped>
.edit-travel-note-container {
  max-width: 1000px;
  margin: 0 auto;
  padding: 20px;
}

.page-header {
  text-align: center;
  margin-bottom: 30px;
}

.page-header h1 {
  font-size: 32px;
  font-weight: 600;
  color: #303133;
  margin: 0 0 10px;
}

.subtitle {
  font-size: 16px;
  color: #909399;
  margin: 0;
}

.loading-container {
  min-height: 400px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.form-card {
  border-radius: 12px;
}

.travel-note-form {
  padding: 20px;
}

.tags-container {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  align-items: center;
}

.tag-item {
  font-size: 14px;
}

.tag-input {
  width: 150px;
}

.form-tip {
  margin-top: 8px;
  font-size: 13px;
  color: #909399;
  display: flex;
  align-items: center;
  gap: 5px;
}

.action-buttons {
  display: flex;
  justify-content: center;
  gap: 20px;
  margin-top: 20px;
}

.action-buttons .el-button {
  min-width: 120px;
}

@media (max-width: 768px) {
  .edit-travel-note-container {
    padding: 15px;
  }

  .page-header h1 {
    font-size: 24px;
  }

  .travel-note-form {
    padding: 10px;
  }

  .action-buttons {
    flex-direction: column;
  }

  .action-buttons .el-button {
    width: 100%;
  }
}
</style>
